﻿// (c) Copyright Damian Mehers http://damianblog.com/
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Xml;
using MceFM.Last;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;
using Microsoft.Win32;

namespace MceFM.Code {
  public class Options : ModelItem {
    private static bool checkedForNewVersion;
    private static string staticNextVersionMessage = "";
    private readonly DateTime currentVersionReleaseDate = new DateTime(2008, 06, 17);
    private string lastFmPassword = "";
    private string lastFmUsername = "";
    private string nextVersionMessage = staticNextVersionMessage;
    private string queueUpCount = "";
    private string savedLastFmPasswordHash;
    private string savedLastFmUsername;
    private string savedQueueUpCount;
    private readonly Settings settings = new Settings();

    public Options() {
      CheckForNewVersion();
      LoadSavedValues();
    }

    /// <summary>
    /// The username that is currently stored in the registry
    /// </summary>
    public string SavedLastFmUsername {
      get {return savedLastFmUsername;}
    }

    /// <summary>
    /// The password hash that is currently stored in the registry
    /// </summary>
    public string SavedLastFmPasswordHash {
      get {return savedLastFmPasswordHash;}
    }

    /// <summary>
    /// The password hash that is currently stored in the registry
    /// </summary>
    public string SavedLastFmPassword {
      get {return savedLastFmPasswordHash;}
    }

    public string SavedQueueUpCount {
      get {return savedQueueUpCount;}
    }


    public string LastFmUsername {
      get {return lastFmUsername;}
      set {lastFmUsername = value;}
    }

    public string LastFmPassword {
      get {return lastFmPassword;}
      set {
        if(lastFmPassword != value) {
          lastFmPassword = value;
        }
      }
    }

    public string QueueUpCount {
      get {return queueUpCount;}
      set {
        if(queueUpCount != value) {
          queueUpCount = value;
          FirePropertyChanged("QueueUpCount");
        }
      }
    }

    public String CurrentVersionMessage {
      get {
        Trace.TraceInformation("Getting current version");
        object[] attributes =  Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
        string version = attributes != null && attributes.Length == 1 ? ((AssemblyProductAttribute)attributes[0]).Product : "";
       
        return version;

      }
    }

    
    public string NextVersionMessage {
      get {return nextVersionMessage;}
      set {
        FirePropertyChanged("NextVersionMessage");
        nextVersionMessage = value;
      }
    }

    private string GetSavedValue(string name, string defaultValue) {
      string returnValue = (string)Registry.GetValue(settings.RegistryRoot, name, "");
      if(string.IsNullOrEmpty(returnValue)) {
        returnValue = (string)Registry.GetValue(settings.GlobalRegistryRoot, name, defaultValue);
      }
      return returnValue;
    }

    private void LoadSavedValues() {
      savedLastFmUsername = GetSavedValue(settings.UsernameRegKey, "");
      savedLastFmPasswordHash = GetSavedValue(settings.PasswordHashRegKey, "");
      savedQueueUpCount = GetSavedValue(settings.QueueUpCountRegKey, settings.DefaultRepeatCount.ToString());
      savedQueueUpCount = string.IsNullOrEmpty(savedQueueUpCount)
                            ? settings.DefaultRepeatCount.ToString()
                            : savedQueueUpCount; // In case it is blank in the registry
    }

    private void CheckForNewVersion() {
      if(checkedForNewVersion) {
        return;
      }
      Thread t = new Thread(CheckForNewVersionThread) {IsBackground = true};
      t.Start();
    }

    private void CheckForNewVersionThread() {
      try {
        WebClient webClient = new WebClient();
        byte[] result = webClient.DownloadData(new Uri("http://www.mcefm.com/LatestVersion.xml"));


        MemoryStream memoryStream = new MemoryStream(result);

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(memoryStream);
        XmlNode releaseDateNode = xmlDocument.SelectSingleNode("/Version/ReleaseDate");
        DateTime nextVersionReleaseDate = DateTime.Parse(releaseDateNode.InnerText);
        if(nextVersionReleaseDate <= currentVersionReleaseDate) {
          Trace.TraceInformation("Next Version Release Date is " + nextVersionReleaseDate);
          return;
        }

        XmlNode messageNode = xmlDocument.SelectSingleNode("/Version/Message");
        NextVersionMessage = messageNode.InnerText;
        staticNextVersionMessage = NextVersionMessage;
        checkedForNewVersion = true;
        Trace.TraceInformation("Set message to " + NextVersionMessage);
      } catch(Exception ex) {
        Trace.TraceError("Error checking for new version: {0}", ex);
      } finally {
        Trace.Flush();
      }
    }


    public void Save() {

      Registry.SetValue(settings.RegistryRoot, settings.UsernameRegKey, lastFmUsername);

      if (!string.IsNullOrEmpty(lastFmPassword)) {
        Registry.SetValue(settings.RegistryRoot, settings.PasswordHashRegKey, Server.GetPasswordHash(lastFmPassword));
      }

      
      Registry.SetValue(settings.RegistryRoot, settings.QueueUpCountRegKey, queueUpCount);
      
      LoadSavedValues();
      ((HistoryOrientedPageSession)PageSession.Current).BackPage();
    }

    public void Cancel() {}
  }
}